<template>
  <div class="demo">
    <div class="demo-title">动态添加和删除</div>
    <div class="demo-content">
      <template v-for="(tag, index) in state.tags" :key="tag">
        <Tooltip v-if="tag.length > 20" :title="tag">
          <Tag :closable="index !== 0" @close="handleClose(tag)">
            {{ `${tag.slice(0, 20)}...` }}
          </Tag>
        </Tooltip>
        <Tag v-else :closable="index !== 0" @close="handleClose(tag)">
          {{ tag }}
        </Tag>
      </template>
      <Input
        v-if="state.inputVisible"
        ref="inputRef"
        v-model:value="state.inputValue"
        type="text"
        size="small"
        :style="{ width: '78px' }"
        @blur="handleInputConfirm"
        @keyup.enter="handleInputConfirm"
      />
      <Tag v-else style="background: #fff; border-style: dashed" @click="showInput">
        <PlusOutlined />
        New Tag
      </Tag>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import Input from '@sscd/input';
  import Tooltip from '@sscd/tooltip';
  import Tag from '@sscd/tag';
  const inputRef = ref();
  const state = reactive({
    tags: ['Unremovable', 'Tag 2', 'Tag 3Tag 3Tag 3Tag 3Tag 3Tag 3Tag 3'],
    inputVisible: false,
    inputValue: '',
  });
  const handleClose = (removedTag: string) => {
    const tags = state.tags.filter((tag) => tag !== removedTag);
    console.log(tags);
    state.tags = tags;
  };
  const showInput = () => {
    state.inputVisible = true;
    nextTick(() => {
      inputRef.value.focus();
    });
  };
  const handleInputConfirm = () => {
    const tempInputValue = state.inputValue;
    let tempTags = state.tags;
    if (tempInputValue && tempTags.indexOf(tempInputValue) === -1) {
      tempTags = [...tempTags, tempInputValue];
    }
    console.log(tempTags);
    Object.assign(state, {
      tags: tempTags,
      inputVisible: false,
      inputValue: '',
    });
  };
</script>
